import { Component, OnInit } from '@angular/core';
import { of } from 'rxjs';
import { delay } from 'rxjs/operators';

const tableData = [
  {name: 'cici', sex: 'female', age: '35'},
  {name: 'amy', sex: 'female', age: '20'},
  {name: 'bella', sex: 'female', age: '32'},
  {name: 'denny', sex: 'male', age: '13'},
  {name: 'eric', sex: 'male', age: '23'},
  {name: 'frank', sex: 'female', age: '46'},
];

/**
 * @title Table sort
 */
@Component({
  selector: 'fui-table-sort',
  templateUrl: './table-sort.component.html',
  styleUrls: ['./table-sort.component.css'],
})
export class TableSortComponent implements OnInit {
  tableData;

  sortMode;

  loading = false;

  constructor() { }

  ngOnInit() {
    this.fetchData().subscribe((data) => {
      this.tableData = data;
    });
  }

  sortChange(changes) {
    console.log('sort changes', changes);
    this.loading = true;
    this.fetchData(changes).subscribe((data) => {
      this.tableData = data;
      this.loading = false;
    });
  }

  fetchData(changes?) {
    if (!changes || (changes.length === 0 && !changes[0].sortedBy)) {
      return of(tableData);
    }

    const {sortedBy, order} = changes;
    const keys: string[] = sortedBy.split(',');
    const orders: string[] = order.split(',');
    const data = tableData.sort((a, b) => {
      let _order;
      const _key = keys.find((key, i) => {
        _order = orders[i];
        return a[key] !== b[key];
      });
      if (_key) {
        const isSmaller = a[_key] < b[_key];
        if (_order === 'desc') {
          return isSmaller ? 1 : -1;
        } else {
          return isSmaller ? -1 : 1;
        }
      }
      return 0;
    });
    return of(data).pipe(delay(1000));
}

  toggleSortMode() {
    if (this.sortMode === 'multiple') {
      this.sortMode = 'single';
    } else {
      this.sortMode = 'multiple';
    }
  }

}
